<template>
  <!-- 安全责任指标考核个人工作项维护 -->
  <base-breadcrumb :breadcrumb="!isAudit">
    <a-card :bordered="false">
      <title-name title="基本信息" />
      <a-form-model ref="form" :model="formInfo" :hideRequiredMark="true">
        <a-row :gutter="24" type="flex">
          <a-col :md="8" :sm="8">
            <a-form-model-item
              label="所属分公司"
              :labelCol="{lg: {span: 6}, sm: {span:6}}"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="branchComId"
              required
            >
            <span v-if="pageType === 'look'">{{formInfo.branchComName}}</span>
              <SelectSubCompany v-else :disabled="isDisabled" v-model="formInfo.branchComId" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item
              label="所属项目"
              :labelCol="{lg: {span: 6}, sm: {span:6}}"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="projectId"
              required
            >
            <span v-if="pageType === 'look'">{{formInfo.projectName}}</span>
              <SelectProject
                v-else
                :disabled="isDisabled"
                v-model="formInfo.projectId"
                keyValue="branchComId"
                :form="formInfo"
                :clear-list="true"
                @change="handleProjectChanged"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" v-if="pageType === 'look' && !isAudit">
            <a-form-model-item
              label="岗位"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="jobId"
            >
                <span>{{formInfo.jobName}}</span>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" v-if="isAudit">
            <a-form-model-item
              label="申请人"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="employeeId"
            >
                <span>{{formInfo.employeeName}}</span>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" v-if="isAudit">
            <a-form-model-item
              label="申请人岗位"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="jobId"
            >
                <span>{{formInfo.jobName}}</span>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <div class="page-body">
      <a-card v-if="!isAudit" :bordered="false" class="body-left">
        <title-name title="岗位列表" />
        <div class="tree-container">
          <JobsTree :selectedKeys.sync="jobSelectedKeys" @select="handleTreeNodeSelect"/>
        </div>
      </a-card>
      <a-card class="body-right">
        <title-name title="安全工作任务清单" />
        <div class="body-right-panel">
          <div class="left-panel" v-if="pageType !== 'look'">
            <div class="table-operateors mb20">
              <a-button type="primary" :loading="loading.isOperating" @click="handleUpdate('addTable')">添加到我的工作项</a-button>
            </div>
            <a-empty v-if="!columns.length"/>
            <s-table
              v-else
              :row-selection="{ selectedRowKeys: selectedRowKeys,  onChange: handleSelectChange}"
              ref="addTable"
              size="default"
              rowKey="id"
              :columns="columns"
              :data="loadData"
              :alert="true"
              show-size-changer
              show-quick-jumper
              :showPagination="false"
              :scroll="{ x: 400, y: 800 }"
            >
              <template slot="serial" slot-scope="text, record, index">{{index + 1}}</template>
              <template slot="operator" slot-scope="text, record">
                <a class="base-btn" @click="handleOperate('edit', record)">编辑</a>
              </template>
            </s-table>
          </div>
          <div class="right-panel">
            <div class="table-operateors mb20" v-if="pageType !== 'look'">
              <a-button type="danger" :loading="loading.isOperating" @click="handleUpdate('removeTable')">从我的工作项移除</a-button>
            </div>
            <a-empty v-if="!realPeronalColumns.length"/>
            <s-table
              v-else
              :row-selection="{ selectedRowKeys: personalSelectedRowKeys, onChange: handlePersonalSelectChange }"
              ref="removeTable"
              size="default"
              rowKey="id"
              :columns="realPeronalColumns"
              :data="loadPersonalData"
              :alert="true"
              show-size-changer
              show-quick-jumper
              :showPagination="false"
              :scroll="{ x: 400, y: 800 }"
            >
              <template slot="serial" slot-scope="text, record, index">{{index + 1}}</template>
              <template slot="operator" slot-scope="text, record">
                <a class="base-btn" @click="handleOperate('edit', record)">编辑</a>
              </template>
            </s-table>
          </div>
        </div>
      </a-card>
    </div>
    <div class="tool-btns page-btn-right-top" v-if="pageType !== 'look'">
      <!-- <a-button type="danger" :loading="loading.DELETE" @click="handleSave('DELETE')">删除草稿</a-button> -->
      <!-- <a-button type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')">保存草稿</a-button> -->
      <a-button type="primary" :loading="loading.SUBMITTED" @click="addPersonalExamSubmit">提交</a-button>
      <a-button type="primary" @click="handleClose">关闭</a-button>
    </div>
    <div class="tool-btns page-btn-right-top" v-else>
      <a-button type="primary" @click="handleClose"  v-if="checkVisibleInDetail">关闭</a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
// 业务说明：个人在不同项目的同一岗位下，考核项可能是不同的（即个人的考核项与岗位、所属项目直接关联）
import SelectSubCompany from '@/components/Select/SelectSubCompany.vue'
import SelectProject from '@/components/Select/SelectProject.vue'
import { STable } from '@/components'
import { getExamHeadersByOrganization, getExamContentByOrganization } from '@/api/safetySupervision/common.js'
import {
  getPersonalExamDetail,
  addPersonalExam,
  deletePersonalExamItem,
  addPersonalExamSubmit,
  getPersonalExamByJob
} from '@/api/safetySupervision/examRecord.js'
import { message, Empty } from 'ant-design-vue'
import JobsTree from '@/components/JobsTree'
import { checkVisibleInDetail } from '@/utils/util'
const columns = []
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    SelectSubCompany,
    SelectProject,
    JobsTree,
    AEmpty: Empty
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      queryId: '',
      safetyCheckMap: [], // 存储增加或删除时，操作的考核项列表
      jobSelectedKeys: [],
      isEdit: false, // 是否为修改
      formInfo: {
        branchComId: '',
        projectId: '',
        postId: ''
      },
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        isOperating: false
      },
      personalList: [], // 个人考核项目列表
      totalList: [], // 总考核项目列表
      totalSelectedList: [], // 总考核项目选中项列表
      selectedRowKeys: [], // 总考核项目选中项key值列表
      personalSelectedRowKeys: [], // 个人考核项目选中项key值列表
      columns: columns, // 模板表头
      peronalColumns: columns, // 个人考核表表头
      queryParam: {},
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return new Promise((resolve, reject) => {
          resolve({
            data: this.totalList
          })
        })
      },
      loadPersonalData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.getPersonalList()
          })
        })
      }
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.pageType = 'look'
          })
        }
      }
    }
  },
  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    realPeronalColumns() {
      return this.peronalColumns.filter((item) => item.code !== '5' && item.code !== '6')
    }
  },
  mounted() {
    this.getDetail()
    this.getPersonalExam()
  },
  methods: {
    // 提交单独调用另一个接口
    async addPersonalExamSubmit() {
      if (this.personalList.length === 0) {
        this.$message.error('没有可提交的考核内容')
        return
      }
      const id = this.$route.query.id || this.queryId
      if (!id) return
      if (this.loading.SUBMITTED) return
      this.loading.SUBMITTED = true
      const params = {
        id: id
      }
      const [err, res] = await addPersonalExamSubmit(params)
      if (!err) {
        this.$message.success('成功')
        this.handleClose()
      }
      this.loading.SUBMITTED = false
    },
    getTemplate(jobId) {
      this.getHeaders(jobId)
      // this.getContent(jobId)
    },
    handleProjectChanged() {
      this.getPersonalExam()
    },
    // 根据项目查询个人考核项列表
    async getPersonalExam() {
      const { projectId } = this.formInfo
      if (!projectId) return
      const params = {
        projectId: projectId
      }
      const [err, res] = await getPersonalExamByJob(params)
      if (!err) {
        this.personalList = res.data.safetyCheckMap || []
        this.peronalColumns = (res.data.headerItemVOS || []).map((item) => {
          return {
            ...item,
            dataIndex: item.id,
            title: item.name
          }
        })
        if (this.personalList.length > 0) {
          this.formInfo.id = res.data.id
          this.isEdit = true
        } else {
          this.isEdit = false
        }
      } else {
        this.personalList = []
        this.peronalColumns = []
      }
      this.$refs.removeTable && this.$refs.removeTable.refresh(true) // 更新表格
    },
    // 查找详情
    async getDetail(callback) {
      const id = this.$route.query.id || this.queryId
      if (!id) return
      const params = {
        id
      }
      const [err, res] = await getPersonalExamDetail(params)
      if (!err) {
        const cacheData = { ...this.formInfo }
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          postId: res.data.jobId
        }
        this.$nextTick(() => {
          this.formInfo.projectId = res.data.projectId
        })
        callback && callback(cacheData) // 赋值完后执行回调,还原之前的postId、jobId数据
        this.jobSelectedKeys.push(this.formInfo.jobId)
        this.getTemplate(this.formInfo.jobId)
        this.personalList = res.data.safetyCheckMap || []
        this.peronalColumns = (res.data.headerItemVOS || []).map((item) => {
          return {
            ...item,
            dataIndex: item.id,
            title: item.name
          }
        })
      } else {
        this.personalList = []
        this.peronalColumns = []
      }
      this.$refs.removeTable && this.$refs.removeTable.refresh(true)
    },
    validateForm() {
      let flag = true
      let message = ''
      const { projectId, postId } = this.formInfo
      if (!projectId) {
        flag = false
        message = '请选择项目'
      }
      if (flag && !postId) {
        flag = false
        message = '请选择岗位'
      }
      if (!flag) {
        this.$message.error(message)
      }
      return flag
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (status !== 'DELETE' && !this.validateForm()) return
      if (this.loading[status]) return
      this.loading[status] = true
      let params = {
        ...this.formInfo,
        safetyCheckMap: this.safetyCheckMap,
        jobId: this.formInfo.postId,
        auditStatusEnum: status,
        id: this.formInfo.id || void 0
      }
      if (status === 'DELETE') {
        // 移除时，参数为id数组
        params = this.safetyCheckMap.map((item) => item.id)
      }
      const fn = addPersonalExam // 添加个人项时，始终调用新增接口
      const map = {
        DELETE: deletePersonalExamItem,
        DRAFT: fn,
        SUBMITTED: fn
      }
      const [err, res] = await map[status](params)
      if (!err) {
        if (res.data.id) {
          this.queryId = res.data.id
        }
        this.$message.success('成功')
        if (status === 'SUBMITTED') {
          this.handleClose()
        } else {
          const { postId } = this.formInfo
          const callback =
            status === 'DELETE'
              ? (data = {}) => {
                  const { postId } = data
                  this.formInfo.jobId = postId
                  this.formInfo.postId = postId
                }
              : null
          this.getDetail(callback) // 获取更新后的个人项列表
        }
      }
      this.loading[status] = false
    },
    // 获取模板内容
    async getContent(id) {
      const [err, res] = await getExamContentByOrganization({ postId: id })
      if (!err) {
        try {
          const dataIndex = this.columns.find((item) => item.code === '4').dataIndex
          this.totalList = (res.data || []).filter((item) => item[dataIndex] === '可用')
        } catch {
          this.totalList = res.data || []
        }
      } else {
        this.totalList = []
      }
      this.$refs.addTable && this.$refs.addTable.refresh(true)
    },
    // 获取模板列
    async getHeaders(id) {
      const [err, res] = await getExamHeadersByOrganization({ postId: id })
      if (!err) {
        const columnList = res.data || []
        columnList.unshift({
          title: '序号',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 65
        })
        this.columns = columnList
        this.getContent(id)
      } else {
        this.columns = []
      }
    },
    handleTreeNodeSelect() {
      const selectedKeys = this.jobSelectedKeys
      if (selectedKeys.length) {
        const postId = selectedKeys[0]
        this.formInfo.postId = postId
        this.getTemplate(postId)
      }
    },
    // 个人考核项选择变化
    handlePersonalSelectChange(selectedRowKeys) {
      this.personalSelectedRowKeys = selectedRowKeys
    },
    // 返回个人考核项列表
    getPersonalList() {
      return this.personalList
    },
    // 总考核项选择变化
    handleSelectChange(selectedRowKeys, selectedRows) {
      this.totalSelectedList = selectedRows
    },
    /**
     * @param {String} name 'addTable' | 'removeTable'
     * @description 对添加、移除操作处理
     */
    async handleUpdate(name) {
      try {
        if (this.loading.isOperating) return
        this.loading.isOperating = true
        if (name === 'addTable') {
          // 添加
          this.safetyCheckMap = [...this.totalSelectedList]
          await this.handleSave('DRAFT')
          this.loading.isOperating = false
          this.selectedRowKeys = []
        } else {
          // 移除
          this.safetyCheckMap = this.personalList.filter((item) => {
            return this.personalSelectedRowKeys.includes(item.id)
          })
          await this.handleSave('DELETE')
          this.loading.isOperating = false
        }
        this.$refs.removeTable && this.$refs.removeTable.refresh(true)
        this.$refs[name] && this.$refs[name].clearSelected() // 清空已选
      } catch {
        this.loading.isOperating = false
      }
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .ant-form-item-children {
  span {
    display: block;
    margin-top: -3px;
  }
}
.page-body {
  display: flex;
  .body-left {
    white-space: nowrap;
    width: 230px;
    @{deep}.ant-card-body {
      display: flex;
      flex-direction: column;
      height: 100%;
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE 10+ */
      ::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }
    }
    .tree-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .body-right {
    flex: auto;
    width: 400px;
    border-left: 1px solid rgba(231, 231, 231, 1);
    .body-right-panel {
      width: 100%;
      display: flex;
      .left-panel,
      .right-panel {
        flex: 1;
      }
      .right-panel {
        margin-left: 20px;
      }
    }
  }
}

.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>